package com.wuze.cloud.adapter;

import com.wuze.cloud.dao.SysFolderDao;
import com.wuze.cloud.enums.SysStateEnum;
import com.wuze.cloud.pojo.SysFileDO;
import com.wuze.cloud.pojo.SysFileShardDO;
import com.wuze.cloud.pojo.SysFolderDO;
import com.wuze.cloud.request.SysFileChunkQuery;
import com.wuze.cloud.response.SysFileVO;
import com.wuze.cloud.util.FileUtil;
import com.wuze.cloud.util.SnowFlakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: wuze
 * @description:
 * @date: 2023/02/21
 */
@Component
public class SysFileAdapter {

    @Autowired
    private SysFolderDao folderDao;

    public SysFileShardDO buildSysFileShardDO(SysFileChunkQuery query){
        SysFileShardDO shard = new SysFileShardDO();
        BeanUtils.copyProperties(query,shard);
        shard.setId(SnowFlakeIdWorker.nextId());
        return shard;
    }

    public SysFileDO buildSysFileDO(SysFileChunkQuery query){
        SysFileDO file = new SysFileDO();
        BeanUtils.copyProperties(query,file);
        file.setId(SnowFlakeIdWorker.nextId());
        file.setFileName(query.getName());
        file.setRealPath(query.getPath());
        file.setState(SysStateEnum.CREATE.name());
        file.setType(FileUtil.getFileType(query.getSuffix()));
        return file;

    }

    public SysFileVO buildSysFileVO(SysFileDO file){
        SysFileVO vo = new SysFileVO();
        BeanUtils.copyProperties(file,vo);
        vo.setSuffix(file.getFileName().substring(file.getFileName().lastIndexOf('.')));
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        vo.setCreateTime(format.format(file.getCreateTime()));
        vo.setUpdateTime(format.format(file.getUpdateTime()));
        return vo;
    }

    public List<SysFileVO> buildSysFileVOS(List<SysFileDO> files){
        List<SysFileVO> vos = new ArrayList<>();
        if(CollectionUtils.isEmpty(files)){
            return vos;
        }
        files.stream().forEach(file->{
            vos.add(buildSysFileVO(file));
        });
        Set<Long> folderIds = files.stream().map(SysFileDO::getFolderId).collect(Collectors.toSet());
        if(CollectionUtils.isEmpty(folderIds)){
            return vos;
        }
        List<SysFolderDO> folders = folderDao.findByIds(folderIds);
        Map<Long, String> folderMap = folders.stream().collect(Collectors.toMap(SysFolderDO::getId, SysFolderDO::getFolderName));
        vos.stream().forEach(vo->{
            vo.setFolderName(folderMap.get(vo.getFolderId()));
        });
        return vos;
    }
}
